/* stdvm.c */
/*The stdvm is wevm important lib. do not change it.*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int write_memory(int offset, char* data, int datasize, char* memory) {
	int ptr = offset;
	int count = 0;
	for(;ptr<offset+datasize;ptr++){
		memory[ptr] = data[count];
		count++;
	}
}
char* read_memory(int offset, int size, char* memory) {
	int ptr = offset;
	int count = 0;
	char* str = (char*)malloc(1024);
	for(;ptr<offset+size;ptr++){
		str[count] = memory[ptr];
		count++;
	}
	return str;
}
int execute(unsigned char bytecode, unsigned char args[], char* memory, FILE* harddisk) {
	char* datas = "";
	switch (bytecode) {
		case 0x01:
			memory[args[2]] = args[0] + args[1];
			break;
		case 0x02:
			memory[args[2]] = args[0] - args[1];
			break;
		case 0x03:
			memory[args[2]] = args[0] * args[1];
			break;
		case 0x04:
			if(args[1] == 0){
				return 2;
			}
			memory[args[2]] = args[0] / args[1];
			break;
		case 0x05:
			return 3;
		case 0x06:
			printf("%s", args);
			break;
        case 0x07:
			printf("%d", memory[args[0]]);
			break;
		case 0x00:
			break;
		case 0x08:
			fputs(args, harddisk);
			break;
		case 0x09:
			memory[args[1]] = fgetc(harddisk);
			break;
		case 0x0A:
			fseek(harddisk, args[1], SEEK_SET);
			break;
		case 0x0B:
			rewind(harddisk);
			break;
		case 0x0C:
			return 4;
		case 0x0D:
			
			fgets(datas, 1024, stdin);
			write_memory(args[0], datas, strlen(datas), memory);
			
			break;
		case 0x0E:
			datas = read_memory(args[0], args[1], memory);
			printf("%s\n", datas);
			free(datas);
			break;
		default:
			printf("Unknown machine code:%x\n", bytecode);
			return 1;
			break;
	}
	return 0;
	
}
